package com.sskj.b70;

import android.support.multidex.MultiDexApplication;
import android.support.v7.app.AppCompatDelegate;
import android.text.TextUtils;

import com.bulong.rudeness.RudenessScreenHelper;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.SPCookieStore;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.shizhefei.mvc.MVCCoolHelper;
import com.sskj.b70.common.AppManager;
import com.sskj.b70.common.BaseActivityLifecycleCallbacks;
import com.sskj.b70.common.Cockroach;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.rxbus2.RxBus;
import com.sskj.b70.mvchelper.LoadViewFactory;
import com.sskj.b70.utils.JsonUtil;
import com.sskj.b70.utils.LanguageUtil;
import com.sskj.b70.utils.LogUtil;
import com.sskj.b70.utils.SPUtils;
import com.sskj.b70.v.activity.LoginActivity;
import com.sskj.b70.v.activity.MainActivity;
import com.tencent.bugly.crashreport.CrashReport;
import com.zxy.recovery.core.Recovery;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;


/**
 * Created by Lee on 2018/1/25 0025.
 */

public class MyAppLication extends MultiDexApplication {

    public static boolean IS_HOME = false;
    public static boolean IS_FIRST_LOCK = true;
    public static MainActivity mainActvity;

    public static MyAppLication getApplication() {
        return mApplication;
    }


    private static MyAppLication mApplication;


    public void logout() {
        RxBus.getDefault().send(Constants.USER_LOGOUT);
        SPUtils.clear();
        OkGo.getInstance().getCommonHeaders().remove("account");
        OkGo.getInstance().getCommonHeaders().remove("id");
        OkGo.getInstance().getCommonHeaders().remove("token");
        OkGo.getInstance().getCommonHeaders().remove("sessionId");
        if (!AppManager.getAppManager().currentActivity().getClass().equals(LoginActivity.class)) {
            MyAppLication.exitApp(MainActivity.class);
            LoginActivity.start(AppManager.getAppManager().currentActivity());
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
//        Stetho.initializeWithDefaults(this);
        new RudenessScreenHelper(this, 750).activate(); //初始化百分比布局
        CrashReport.initCrashReport(getApplicationContext(), "bb1245b532", false);
        registerActivityLifecycleCallbacks(new BaseActivityLifecycleCallbacks());
        initOkgoHttp();
        IS_HOME = false;
//        LeakCanary.install(this);
        Recovery.getInstance()
                .debug(!BuildConfig.RELEASE)
                .recoverInBackground(false)
                .recoverStack(true)
                .mainPage(MainActivity.class)
                .recoverEnabled(true)
                .callback(null)
                .silent(false, Recovery.SilentMode.RECOVER_ACTIVITY_STACK)
                .init(this);
        MVCCoolHelper.setLoadViewFractory(new LoadViewFactory());
        // 默认设置为日间模式
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        LanguageUtil.changeAppLanguage(this, LanguageUtil.getAppLocale(this), true);

    }

    public void removeAllHttpParam() {
        OkGo.getInstance().getCommonHeaders().clear();
        OkGo.getInstance().getCommonParams().clear();
        OkGo.getInstance().getCommonParams().put("systemType", "ANDROID");
        OkGo.getInstance().getCommonHeaders().put("systemType", "ANDROID");
    }

    public void initOkgoHttp() {
        LogUtil.init(BuildConfig.LOG_DEBUG);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)))
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS);
        setColorfulLog(builder);
        HttpHeaders headers = new HttpHeaders();
        headers.clear();
        headers.put("account", TextUtils.isEmpty(getAccount()) ? null : getAccount());    //所有的 header 都 不支持 中文
        headers.put("sessionId", TextUtils.isEmpty(getSessionId()) ? null : getSessionId());
        headers.put("id", TextUtils.isEmpty(getID()) ? null : getID());
        HttpParams httpParams = new HttpParams();
        httpParams.clear();
        httpParams.put("systemType", "ANDROID");
        httpParams.put("account", TextUtils.isEmpty(getAccount()) ? null : getAccount());    //所有的 header 都 不支持 中文
        httpParams.put("sessionId", TextUtils.isEmpty(getSessionId()) ? null : getSessionId());
        httpParams.put("id", TextUtils.isEmpty(getID()) ? null : getID());
        OkGo.getInstance().init(this)//必须调用初始化
                .setOkHttpClient(builder.build())//必须设置OkHttpClient
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .addCommonParams(httpParams)
                .addCommonHeaders(headers)
                .setRetryCount(0);
    }

    private void setColorfulLog(OkHttpClient.Builder builder) {
        okhttp3.logging.HttpLoggingInterceptor logInterceptor = new okhttp3.logging.HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(okhttp3.logging.HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(logInterceptor);
    }

    private void setWithLog(OkHttpClient.Builder builder) {
        com.lzy.okgo.interceptor.HttpLoggingInterceptor loggingInterceptor = new com.lzy.okgo.interceptor.HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(com.lzy.okgo.interceptor.HttpLoggingInterceptor.Level.BODY);
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);
    }

    private class HttpLogger implements HttpLoggingInterceptor.Logger {
        private StringBuilder mMessage = new StringBuilder();

        @Override
        public void log(String message) {
            // 请求或者响应开始
            if (message.startsWith("--> HTTP FAILD")) {
                LogUtil.d(message);
                return;
            }
            if (message.startsWith("--> POST") || message.startsWith("--> GET")) {
                mMessage.setLength(0);
            }
            // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
            if ((message.startsWith("{") && message.endsWith("}"))
                    || (message.startsWith("[") && message.endsWith("]"))) {
                message = JsonUtil.formatJson(message);
            }
            mMessage.append(message.concat("\n"));
            // 请求或者响应结束，打印整条日志
            if (message.startsWith("<-- END HTTP") || message.startsWith("--> END GET")) {
                LogUtil.d(mMessage.toString());
            }
        }
    }

    public static String getSessionId() {
        return (String) SPUtils.get(mApplication, Constants.SP_SESSIONID, "");
    }

    public static String getMobile() {
        return (String) SPUtils.get(mApplication, Constants.SP_MOBILE, "");
    }

    public static String getAccount() {
        return (String) SPUtils.get(mApplication, Constants.SP_ACCOUNT, "");
    }

    public static String getEmail() {
        return (String) SPUtils.get(mApplication, Constants.SP_EMAIL, "");
    }

    public static boolean isLogin() {
        return (boolean) SPUtils.get(MyAppLication.getApplication(), Constants.SP_LOGIN_STATUS, false);
    }

    public static boolean isShop() {
        return (boolean) SPUtils.get(MyAppLication.getApplication(), Constants.SP_IS_SHOP, false);
    }

    public static String getName() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_REALNAME, "");
    }

    public static String getIdCard() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_IDCORD, "");
    }

    public static String getJGCode() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_JGCODE, "");
    }

    public static String getID() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_ID, "");
    }

    public static String getTel() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_TEL, "");
    }

    public static String getAccountPer() {
        return (String) SPUtils.get(MyAppLication.getApplication(), Constants.SP_ACCOUNTPER, "");
    }

    /**
     * 实名认证状态 2-审核中 ， 3-已认证， 4-认证失败
     */
    public static int getRealnameStatus() {
        return (int) SPUtils.get(MyAppLication.getApplication(), Constants.SP_REALNAME_STATUS, 0);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        Cockroach.uninstall();
    }

    /**
     * 退出应用
     *
     * @param mainActivityClass
     */
    public static void exitApp(Class<MainActivity> mainActivityClass) {
        AppManager.getAppManager().finishAllActivity(mainActivityClass);
    }
}
